<template>
  <div class="appointment-time-container">
    <el-card>
      <template #header>
        <h3>我的工单列表</h3>
      </template>

      <!-- 工单列表 -->
      <el-table
        :data="myWorkOrders"
        border
        stripe
        v-loading="isLoading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="_id" label="工单编号" width="180" />
        <el-table-column prop="customer_name" label="客户姓名" width="120" />
        <el-table-column prop="customer_phone" label="联系电话" width="150" />
        <el-table-column prop="user_claim" label="问题描述" min-width="200" />
        <el-table-column prop="status" label="状态" min-width="200" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="router.push(`/${scope.row._id}`)">
              查看详情
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleSelectTime(scope.row)"
              :disabled="scope.row.status !== '待预约'"
            >
              选择时间
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 选择时间模态框 -->
      <el-dialog
        v-model="showTimeDialog"
        title="选择预约时间"
        width="30%"
        :before-close="handleDialogClose"
      >
        <el-form :model="timeForm" label-width="80px">
          <el-form-item label="预约时间" prop="appointment_time">
            <el-date-picker
              v-model="timeForm.appointment_time"
              type="datetime"
              placeholder="选择日期时间"
              :disabled="isSubmitting"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showTimeDialog = false" :disabled="isSubmitting">取消</el-button>
            <el-button
              type="primary"
              @click="confirmAppointment"
              :loading="isSubmitting"
              :disabled="!timeForm.appointment_time || isSubmitting"
            >
              确认预约
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getWorkOrdersByUserId } from '@/api/workOrder' // 按状态获取工单接口
import { setAppointmentTimeByUser } from '@/api/workOrder' // 选择预约时间接口
import { ElMessage } from 'element-plus'
import router from '@/router'

// 状态管理
const myWorkOrders = ref([]) // 当前用户的待预约工单列表
const isLoading = ref(false) // 工单加载状态
const showTimeDialog = ref(false) // 时间选择模态框显示状态
const timeForm = ref({
  // 预约时间表单
  appointment_time: null,
  customer_id: '',
})
const currentOrderId = ref('') // 当前操作的工单ID
const isSubmitting = ref(false) // 提交加载状态

// 初始化：获取当前用户ID并加载待预约工单
onMounted(async () => {
  // 从localStorage获取用户信息（假设登录后存储）
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  if (userInfo) {
    timeForm.value.customer_id = userInfo._id // 假设用户ID字段为_id
  }

  // 加载待预约工单（状态为'pending_appointment'）
  isLoading.value = true
  try {
    const res = await getWorkOrdersByUserId(timeForm.value.customer_id)
    if (res.code === 200) {
      myWorkOrders.value = res.data
    }
  } catch (err) {
    ElMessage.error('获取待预约工单失败', err)
  } finally {
    isLoading.value = false
  }
})

// 点击选择时间按钮
const handleSelectTime = (row) => {
  currentOrderId.value = row._id // 假设工单数据包含_id字段
  timeForm.value.appointment_time = null // 重置时间选择
  showTimeDialog.value = true
}

// 确认预约时间
const confirmAppointment = async () => {
  if (!currentOrderId.value || !timeForm.value.appointment_time) return

  isSubmitting.value = true
  try {
    const res = await setAppointmentTimeByUser(currentOrderId.value, {
      appointment_time: timeForm.value.appointment_time,
      customer_id: timeForm.value.customer_id,
    })
    if (res.code === 200) {
      ElMessage.success('预约时间提交成功')
      showTimeDialog.value = false
      // 刷新工单列表
      const resFresh = await getWorkOrdersByUserId(timeForm.value.customer_id)
      myWorkOrders.value = resFresh.data
    } else {
      ElMessage.error(res.message || '提交失败')
    }
  } catch (err) {
    ElMessage.error('网络请求失败', err)
  } finally {
    isSubmitting.value = false
  }
}

// 关闭模态框
const handleDialogClose = () => {
  showTimeDialog.value = false
  currentOrderId.value = ''
}
</script>

<style scoped>
.appointment-time-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
